#include <iostream>
#include "controller.h"

Controller::Controller(void):lstate(LOGIN_NO),beatInterval(10)
{
	lastrecv = lastsend = lastbeat = time(0);
}
bool Controller::sendTimeout(void)
{
	if(abs(time(0) - lastsend) > 30)
	{
		lastsend += 3;
		return true;
	}
	return false;
}
bool Controller::recvTimeout(void)
{
	int diff = abs(time(0) - lastrecv);
	if(diff > 600)
	{
		lastrecv++;
		printf("%d seconds no recving\n", diff);
		return true;
	}
	return false;
}
bool Controller::beatTimeout(void)
{
	time_t now = time(0);

	if(abs(now - lastbeat) > beatInterval)
	{
		lastbeat = now;
		return true;
	}
	return false;
}
bool Controller::receive(void)
{
	uint8_t c = 0;
	ACE_Time_Value t(0, 1000);

	if(recv_n(&c, 1, &t)==1)
	{
		recvbuf.push(c);
		lastrecv = time(0);
		lastbeat = lastrecv;
		return true;
	}
	return false;
}
bool Controller::sendout(void)
{
	Buffer& b = sendbuf;
	if(send_n(b.buffer, b.length) == b.length)
	{
		lastsend = time(0);
		return true;
	}
	return false;
}
bool Controller::check(void)
{
	return recvbuf.check();
}
bool Controller::login(void)
{
	if(lstate == LOGIN_SEND)
	{
		time_t now = time(0);
		if(abs(now - lastlog) < 3)
		{
			return false;
		}
		lastlog = now;
	}
	sequence = 0;
	makeLogin();
	Buffer& b = sendbuf;
	cout << __func__ << b.toString() << endl;
	if(send_n(b.buffer, b.length) == b.length)
	{
		lstate = LOGIN_SEND;
		return false;
	}
	return false;
}
bool Controller::heatbeat(void)
{
	if(lstate != LOGIN_OK)
	{
		return login();
	}
	if(beatTimeout() == false)
	{
		return false;
	}
	makeHeartbeat();
	Buffer& b = sendbuf;
	if(send_n(b.buffer, b.length) == b.length)
	{
		lastsend = time(0);
		cout << __func__ << b.toString() << endl;
	}
	return true;
}
